package dao

import (
	"context"

	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/system_admin"
	"sale-admin/internal/dal"
	"sale-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/logx"
	"gorm.io/gorm"
)

type MerchantConfig struct{}

func (MerchantConfig) GetDetail(ctx context.Context, db *gorm.DB, ID string) (ShopInfo *models.MaMerchantConfig, count int64, err error) {
	m := dal.Use(db).MaMerchantConfig
	tx := m.WithContext(ctx).
		Where(m.Deleted.Eq(0))
	if ID != "" {
		tx = tx.Where(m.ID.Eq(ID))
	}
	count, _ = tx.Count()
	info, _ := tx.Take()
	if count == 0 {
		if ID != "1" { // 非管理员
			// grpc验证
			SystemAdminClient, clientErr := client.GetSystemAdminClient()
			if clientErr != nil {
				logx.Error(context.Background(), "grpc system admin client error", logx.Err(clientErr))
				return ShopInfo, count, clientErr
			}
			req := &system_admin.MerchantInfoReq{}
			req.MerchantId = ID
			res, err1 := SystemAdminClient.MerchantInfo(context.Background(), req)
			if res != nil && res.Code == 0 && err1 == nil {
				var myInfo models.MaMerchantConfig
				myInfo.ID = ID
				myInfo.Username = res.MerchantName
				db.Model(&models.MaMerchantConfig{}).Create(&myInfo)
				return &myInfo, 1, nil
			} else {
				return ShopInfo, count, errorx.New("商户ID非法", -1)
			}
		}
	}
	return info, count, nil
}
